<template>
  <div class="qualification-rate-analysis" v-loading="loading">
    <el-row :gutter="20">
      <!-- 合格率汇总卡片 -->
      <el-col :span="24">
        <el-card shadow="hover" class="summary-card">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :md="8">
              <div class="summary-item">
                <div class="item-title">总检验数</div>
                <div class="item-value">{{ (chartData.summary.totalCount || 0) | formatNumber }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <div class="summary-item">
                <div class="item-title">合格数</div>
                <div class="item-value">{{ (chartData.summary.qualifiedCount || 0) | formatNumber }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <div class="summary-item">
                <div class="item-title">合格率</div>
                <div class="item-value" :class="rateColorClass">{{ (chartData.summary.qualificationRate || 0) }}%</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 合格率趋势图 -->
    <el-row :gutter="20" class="chart-row" v-if="chartData.trend && chartData.trend.length > 0">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>合格率趋势分析</span>
            <el-tooltip content="展示合格率的时间变化趋势，红线为90%合格率下限" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
          <div class="chart-container" ref="trendChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 按维度统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="24" :md="12" v-if="chartData.productStats && chartData.productStats.length > 0">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>产品合格率比较</span>
          </div>
          <div class="chart-container" ref="productChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" v-if="chartData.batchStats && chartData.batchStats.length > 0">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>批次合格率比较</span>
          </div>
          <div class="chart-container" ref="batchChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24" v-if="chartData.processStats && chartData.processStats.length > 0">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>工序合格率比较</span>
          </div>
          <div class="chart-container" ref="processChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getQualificationTrend } from "@/api/qep/dataAnalysis";

export default {
  name: "QualificationRateAnalysis",
  props: {
    queryParams: {
      type: Object,
      required: true
    },
    chartData: {
      type: Object,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      trendChart: null,
      productChart: null,
      batchChart: null,
      processChart: null,
      timeGranularity: 'day'
    }
  },
  computed: {
    rateColorClass() {
      const rate = this.chartData.summary.qualificationRate || 0;
      if (rate >= 98) return 'text-success';
      else if (rate >= 90) return 'text-warning';
      else return 'text-danger';
    }
  },
  watch: {
    'chartData': {
      handler() {
        this.$nextTick(() => {
          this.initCharts();
        });
      },
      deep: true
    },
    'loading': {
      handler(newVal) {
        if (!newVal) {
          this.$nextTick(() => {
            this.initCharts();
          });
        }
      }
    }
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    initCharts() {
      this.initTrendChart();
      this.initProductChart();
      this.initBatchChart();
      this.initProcessChart();
    },
    
    resizeCharts() {
      try {
        // 只在实例存在且DOM元素存在时尝试调整大小
        if (this.trendChart && this.$refs.trendChart && this.trendChart.resize) {
          this.trendChart.resize();
        }
        
        if (this.productChart && this.$refs.productChart && this.productChart.resize) {
          this.productChart.resize();
        }
        
        if (this.batchChart && this.$refs.batchChart && this.batchChart.resize) {
          this.batchChart.resize();
        }
        
        if (this.processChart && this.$refs.processChart && this.processChart.resize) {
          this.processChart.resize();
        }
      } catch (error) {
        console.error('Error resizing charts:', error);
      }
    },
    
    disposeCharts() {
      this.trendChart?.dispose();
      this.productChart?.dispose();
      this.batchChart?.dispose();
      this.processChart?.dispose();
    },
    
    initTrendChart() {
      if (!this.$refs.trendChart) return;
      
      try {
        if (this.trendChart) {
          this.trendChart.dispose();
        }
        
        this.trendChart = echarts.init(this.$refs.trendChart);
        
        const trendData = this.chartData.trend || [];
        const xData = trendData.map(item => item.timePoint);
        const yData = trendData.map(item => item.qualificationRate);
        
        // 只有当有数据时才设置完整的配置
        if (xData.length > 0 && yData.length > 0) {
          const option = {
            tooltip: {
              trigger: 'axis',
              formatter: '{b}<br/>{a}: {c}%'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xData,
              axisLabel: {
                rotate: xData.length > 10 ? 45 : 0,
                interval: xData.length > 20 ? 'auto' : 0
              }
            },
            yAxis: {
              type: 'value',
              min: 0, 
              max: 100,
              axisLabel: {
                formatter: '{value}%'
              }
            },
            series: [
              {
                name: '合格率',
                type: 'line',
                smooth: true,
                data: yData,
                itemStyle: {
                  color: '#1890ff'
                },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
                    { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
                  ])
                },
                emphasis: {
                  focus: 'series'
                },
                markLine: {
                  silent: true,
                  lineStyle: { color: '#f56c6c' },
                  data: [
                    { yAxis: 90, name: '合格率下限', label: { formatter: '90%', position: 'insideEndTop' } }
                  ].filter(item => item.yAxis !== null && item.yAxis !== undefined && !isNaN(item.yAxis))
                }
              }
            ]
          };
          this.trendChart.setOption(option, true);
        } else {
          // 无数据时显示提示信息
          this.trendChart.setOption({
            title: {
              text: '暂无趋势数据',
              left: 'center',
              top: 'center',
              textStyle: { color: '#888' }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
        }
      } catch (error) {
        console.error('Failed to initialize trend chart:', error);
      }
    },
    
    initProductChart() {
      if (!this.$refs.productChart) return;
      
      try {
        if (this.productChart) {
          this.productChart.dispose();
        }
        
        this.productChart = echarts.init(this.$refs.productChart);
        
        const productStats = this.chartData.productStats || [];
        if (productStats.length === 0) {
          // 显示无数据提示
          this.productChart.setOption({
            title: {
              text: '暂无产品合格率数据',
              left: 'center',
              top: 'center',
              textStyle: { color: '#888' }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
          return;
        }
        
        const data = productStats.map(item => ({
          name: item.productName,
          value: item.qualificationRate
        }));
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
              rotate: data.length > 5 ? 45 : 0,
              interval: 0
            }
          },
          yAxis: {
            type: 'value',
            min: 'dataMin',
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          },
          series: [
            {
              type: 'bar',
              data: data.map(item => item.value),
              itemStyle: {
                color: params => {
                  const value = params.value;
                  if (value >= 98) return '#67c23a';
                  else if (value >= 90) return '#e6a23c';
                  else return '#f56c6c';
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}%'
              }
            }
          ]
        };
        
        this.productChart.setOption(option);
      } catch (error) {
        console.error('Failed to initialize product chart:', error);
      }
    },
    
    initBatchChart() {
      if (!this.$refs.batchChart) return;
      
      try {
        if (this.batchChart) {
          this.batchChart.dispose();
        }
        
        this.batchChart = echarts.init(this.$refs.batchChart);
        
        const batchStats = this.chartData.batchStats || [];
        if (batchStats.length === 0) {
          // 显示无数据提示
          this.batchChart.setOption({
            title: {
              text: '暂无批次合格率数据',
              left: 'center',
              top: 'center',
              textStyle: { color: '#888' }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
          return;
        }
        
        const data = batchStats.map(item => ({
          name: item.batchNo,
          value: item.qualificationRate
        }));
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
              rotate: data.length > 5 ? 45 : 0,
              interval: 0
            }
          },
          yAxis: {
            type: 'value',
            min: 'dataMin',
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          },
          series: [
            {
              type: 'bar',
              data: data.map(item => item.value),
              itemStyle: {
                color: params => {
                  const value = params.value;
                  if (value >= 98) return '#67c23a';
                  else if (value >= 90) return '#e6a23c';
                  else return '#f56c6c';
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}%'
              }
            }
          ]
        };
        
        this.batchChart.setOption(option);
      } catch (error) {
        console.error('Failed to initialize batch chart:', error);
      }
    },
    
    initProcessChart() {
      if (!this.$refs.processChart) return;
      
      try {
        if (this.processChart) {
          this.processChart.dispose();
        }
        
        this.processChart = echarts.init(this.$refs.processChart);
        
        const processStats = this.chartData.processStats || [];
        if (processStats.length === 0) {
          // 显示无数据提示
          this.processChart.setOption({
            title: {
              text: '暂无工序合格率数据',
              left: 'center',
              top: 'center',
              textStyle: { color: '#888' }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
          return;
        }
        
        // 根据合格率从高到低排序
        const sortedData = [...processStats].sort((a, b) => b.qualificationRate - a.qualificationRate);
        
        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              const data = params[0].data;
              return `${params[0].name}<br/>
                     合格率: ${data.qualificationRate}%<br/>
                     合格数: ${data.qualifiedCount}<br/>
                     总数: ${data.totalCount}`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            min: 'dataMin',
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          },
          yAxis: {
            type: 'category',
            data: sortedData.map(item => item.processName),
            axisLabel: {
              interval: 0
            }
          },
          series: [
            {
              type: 'bar',
              data: sortedData.map(item => ({
                value: item.qualificationRate,
                qualificationRate: item.qualificationRate,
                qualifiedCount: item.qualifiedCount,
                totalCount: item.totalCount
              })),
              itemStyle: {
                color: params => {
                  const value = params.value;
                  if (value >= 98) return '#67c23a';
                  else if (value >= 90) return '#e6a23c';
                  else return '#f56c6c';
                }
              },
              label: {
                show: true,
                position: 'right',
                formatter: '{c}%'
              }
            }
          ]
        };
        
        this.processChart.setOption(option);
      } catch (error) {
        console.error('Failed to initialize process chart:', error);
      }
    },
    
    handleGranularityChange(value) {
      this.$emit('update:loading', true);
      getQualificationTrend({
        ...this.queryParams,
        timeGranularity: value
      }).then(response => {
        const trend = response.data.trend || [];
        this.$set(this.chartData, 'trend', trend);
        this.$emit('update:loading', false);
      }).catch(() => {
        this.$emit('update:loading', false);
      });
    }
  },
  filters: {
    formatNumber(value) {
      if (!value) return '0';
      return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
  }
}
</script>

<style scoped>
.qualification-rate-analysis {
  padding: 10px 0;
}
.summary-card {
  margin-bottom: 20px;
}
.summary-item {
  text-align: center;
  padding: 10px 0;
}
.item-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.item-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}
.text-success {
  color: #67c23a;
}
.text-warning {
  color: #e6a23c;
}
.text-danger {
  color: #f56c6c;
}
.chart-row {
  margin-bottom: 20px;
}
.chart-card {
  height: 100%;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  height: 300px;
  width: 100%;
}
</style> 